import 'package:android_intent_plus/android_intent.dart';
import 'package:app_settings/app_settings.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';
import '../../config/theme_color.dart';
import '../privacy/dialog_common_view.dart';
import 'dart:io';

class ImagePickerUtils {
  static Future<XFile?> getCameraImage() async {
    final image = await ImagePicker().pickImage(source: ImageSource.camera);
    if (image != null) {
      return image;
    }
    return null;
  }

  //拍照操作
  static Future<XFile?> takePhotoImage({Function? permissionBack}) async {
    if (Platform.isIOS) {
      var status = Permission.camera.status;
      if (await status.isDenied) {
        await Permission.camera.request();
        return null;
      } else if (await status.isGranted) {
        final image = await getCameraImage();
        return image;
      } else {
        if (permissionBack != null) {
          permissionBack();
        }
        return null;
      }
    } else {
      if (await Permission.camera.request().isGranted) {
        final image = await getCameraImage();
        return image;
      } else {
        if (permissionBack != null) {
          permissionBack();
        }
        return null;
      }
    }
  }

  static Future<XFile?> getAlbumImage() async {
    final image = await ImagePicker().pickImage(source: ImageSource.gallery);
    if (image != null) {
      return image;
    }
    return null;
  }

  //相册导入
  static Future<XFile?> getPhotoFromAlbum({Function? permissionBack}) async {
    if (Platform.isAndroid) {
      final bool isHas = await isHasAlbumPermission();
      if (isHas == true) {
        final image = await getAlbumImage();
        return image;
      } else {
        if (permissionBack != null) {
          permissionBack();
        }
        return null;
      }
    } else {
      if (await Permission.photos.request().isGranted ||
          await Permission.photosAddOnly.request().isGranted) {
        final image = await getAlbumImage();
        return image;
      }
      if (await Permission.photos.request().isDenied) {
        await Permission.photos.request();
        return null;
      } else {
        if (permissionBack != null) {
          permissionBack();
        }
        return null;
      }
    }
  }

  static Future<bool> isHasAlbumPermission() async {
    final androidInfo = await DeviceInfoPlugin().androidInfo;
    if (androidInfo.version.sdkInt <= 32) {
      if (await Permission.storage.request().isGranted) {
        return true;
      }
    } else {
      if (await Permission.photos.request().isGranted) {
        return true;
      }
    }
    return false;
  }

  static void selectPhotoFromSheet(
    context, {
    Function? callBackUrl,
  }) async {
    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return SizedBox(
            height: 220.0,
            child: Container(
                alignment: Alignment.center,
                color: Colors.white,
                child: Column(
                  children: [
                    GestureDetector(
                        onTap: () {
                          Navigator.pop(context);
                          takePhotoImage(permissionBack: () {
                            showAlertAlbum(context,
                                contentStr: '您未开启相机权限，请打开相机权限');
                          }).then((image) {
                            if (callBackUrl != null) {
                              callBackUrl(image?.path);
                            }
                          });
                        },
                        child: Container(
                          alignment: Alignment.center,
                          height: 55,
                          color: Colors.white,
                          child: const Text('拍照'),
                        )),
                    Divider(
                      color: ThemeColor.sendMsgColor,
                      height: 1,
                    ),
                    GestureDetector(
                        onTap: () {
                          Navigator.pop(context);
                          getPhotoFromAlbum(permissionBack: () {
                            showAlertAlbum(context);
                          }).then((image) {
                            if (callBackUrl != null) {
                              callBackUrl(image?.path);
                            }
                          });
                        },
                        child: Container(
                          alignment: Alignment.center,
                          height: 60,
                          color: Colors.white,
                          child: const Text('从手机相册选择'),
                        )),
                    Divider(
                      color: ThemeColor.sendMsgColor,
                      thickness: 7,
                      height: 1,
                    ),
                    GestureDetector(
                      onTap: () {
                        Navigator.pop(context);
                      },
                      child: Container(
                        alignment: Alignment.center,
                        height: 55,
                        child: const Text('取消'),
                      ),
                    ),
                  ],
                )));
      },
    );
  }

  static void selectPhotoAndVideoFromSheet(context,
      {Function? callBackUrl}) async {
    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return SizedBox(
            height: 220.0,
            child: Container(
                alignment: Alignment.center,
                color: Colors.white,
                child: Column(
                  children: [
                    GestureDetector(
                        onTap: () {
                          Navigator.pop(context);
                          getPhotoFromAlbum(permissionBack: () {
                            showAlertAlbum(context);
                          }).then((image) {
                            if (callBackUrl != null) {
                              callBackUrl(image?.path);
                            }
                          });
                        },
                        child: Container(
                          alignment: Alignment.center,
                          height: 55,
                          color: Colors.white,
                          child: const Text('选择图片'),
                        )),
                    Divider(
                      color: ThemeColor.sendMsgColor,
                      height: 1,
                    ),
                    GestureDetector(
                        onTap: () {
                          Navigator.pop(context);
                          selectVideoFromAlbum(permissionBack: () {
                            showAlertAlbum(context);
                          }).then((value) {
                            if (callBackUrl != null) {
                              callBackUrl(value);
                            }
                          });
                        },
                        child: Container(
                          alignment: Alignment.center,
                          height: 60,
                          color: Colors.white,
                          child: const Text('选择视频'),
                        )),
                    Divider(
                      color: ThemeColor.sendMsgColor,
                      thickness: 7,
                      height: 1,
                    ),
                    GestureDetector(
                      onTap: () {
                        Navigator.pop(context);
                      },
                      child: Container(
                        alignment: Alignment.center,
                        height: 55,
                        child: const Text('取消'),
                      ),
                    ),
                  ],
                )));
      },
    );
  }

  static Future<String?> getVideoFromAlbum() async {
    var video = await ImagePicker().pickVideo(source: ImageSource.gallery);
    if (video != null) {
      return video.path;
    }
    return null;
  }

//选择视频
  static Future<String?> selectVideoFromAlbum(
      {Function? permissionBack}) async {
    if (Platform.isAndroid) {
      final bool isHas = await isHasAlbumPermission();
      if (isHas == true) {
        var video = await getVideoFromAlbum();
        return video;
      } else {
        if (permissionBack != null) {
          permissionBack();
        }
        return null;
      }
    } else {
      var status = Permission.photos.status;
      if (await status.isGranted) {
        var video = await getVideoFromAlbum();
        return video;
      } else if (await status.isDenied) {
        await Permission.photos.request();
        return null;
      } else {
        if (permissionBack != null) {
          permissionBack();
        }
        return null;
      }
    }
  }

  //弹出权限设置提醒
  static showAlertAlbum(BuildContext context, {String? contentStr}) {
    ConfirmAlertDialog.showView(context,
        title: '权限设置',
        content: contentStr ?? '您未开启相册/存储权限，请打开相册/存储权限',
        isShowCancelBtn: true, rightAction: () {
      if (Platform.isAndroid) {
        onTapItem();
      } else {
        AppSettings.openAppSettings(type: AppSettingsType.settings);
      }
    });
  }

  static void onTapItem() async {
    AndroidIntent intent = const AndroidIntent(
      action: "android.settings.APPLICATION_DETAILS_SETTINGS",
      package: "com.aispheretech.xinghehuayu",
      data: "package:com.aispheretech.xinghehuayu",
    );
    intent.launch();
    await intent.launch();
  }
}
